#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <uci.h>
#include <uci_cmd.h>

int chilli_set_section ( char *strSection );
int chilli_set_option ( char *strSection, char *strOption, char *strValue );


int main(void)
{

	ctx = uci_alloc_context();
	if (!ctx){
		printf("%s\n","Error al tratar de alojar uci_context");
		return;
	}
	uci_add_history_path(ctx, ctx->savedir);
	uci_set_savedir(ctx, "/var/state");

	int ret;
//	ret = chilli_set_section ( "user10" );
//	ret = chilli_set_option ( "user11", "option_name", "option_value" );
//	ret = chilli_set_option ( "user11", "option_name1", "option_value" );
//	ret = chilli_set_option ( "user11", "option_name2", "option_value" );
//	ret = chilli_set_option ( "user11", "option_name3", "option_value" );
//	ret = chilli_set_option ( "user12", "option_name4", "option_value" );
//	ret = chilli_set_option ( "user11", "option_name4", "option_value" );
//	ret = chilli_set_option ( "user11", "option_name3", "option_value2" );
//	ret = chilli_set_option ( "user11", "option_name3", "option_value3" );
	ret = uci_do_cmd( ctx, CMD_REVERT, "hotspot.user12" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user12=connection" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user12.option1=Value1" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user12.option2=Value2" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user12.option3=Value3" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user12.option4=Value4" );
	ret = uci_do_cmd( ctx, CMD_ADD_LIST, "hotspot.user12.option4=Value5" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user14=connection" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user14.option1=Value1" );
	ret = uci_do_cmd( ctx, CMD_SET, "hotspot.user14.option2=Value2" );
	ret = uci_do_cmd( ctx, CMD_RENAME, "hotspot.user14=user10" );
//  printf("%s", uci_do_cmd ( ctx, CMD_GET, "hotspot.user12.option4" ));

	uci_free_context(ctx);

	return ret;
}

int chilli_set_section ( char *strSection ) {
	char *param;
	int ret;
	int intSize;
	intSize = strlen(strSection)+20;
	param = malloc(intSize);
	memset(param,0,intSize);
//	sprintf(param,"hotspot.%s=connection", strSection);
//printf("set_section %s\n",param);
	ret = uci_do_cmd(ctx,CMD_SET,param);
	free(param);
	return ret;
}

int chilli_set_option ( char *strSection, char *strOption, char *strValue ) {
	char *param;
	int ret;
	int intSize;
	intSize = strlen(strSection) + strlen(strOption) + strlen(strValue)+11;
	param = malloc(intSize);
	memset(param,0,intSize);
	// Check if section exists if not create it
	sprintf(param,"hotspot.%s=connection", strSection);
	ret = uci_do_cmd( ctx, CMD_SET, param );
	// If option exists delete it
	sprintf(param,"hotspot.%s.%s", strSection, strOption );
	ret = uci_do_cmd( ctx, CMD_REVERT, param );
	// Set option value
	sprintf(param,"hotspot.%s.%s=%s", strSection, strOption, strValue);
	ret = uci_do_cmd( ctx, CMD_SET, param );
	free(param);
	return ret;
}
